﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CrmApplication.Models;

namespace CrmApplication.Controllers
{
    public class SubdomainController : Controller
    {
        //
        // GET: /Subdomain/

        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// get all subdomains for selected domain(select by id)
        /// </summary>
        /// <returns></returns>
        public ActionResult GetSubdomain()
        {
            string searchCounty = Request.Params["query"];
            decimal parentId = 0;
            Decimal.TryParse(Request.Params["domain_id"], out parentId);

            SubdomainContainer container = SubdomainModels.GetSubdomainArray(searchCounty, parentId);
            return Json(container, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// add new subdomain
        /// </summary>
        /// <returns></returns>
        public ActionResult AddSubdomain()
        {
            string subdomain = Request.Params["subdomain"];
            decimal parentId = 0;
            Decimal.TryParse(Request.Params["domain"], out parentId);
			string messageBack = null;

			try
			{
				if (subdomain != "")
				{
					SubdomainModels.AddSubdomain(subdomain, parentId);
					messageBack = "Subdomeniul a fost adaugat cu succes!";
				}

				return Json(new { success = true, description = messageBack });
			}
			catch (Exception ex)
			{
				if (ex.Message.Contains("unique key constraint"))
				{
					messageBack = "Exista deja o inregistrare cu acelasi nume";
				}
				return Json(new { success = true, description = messageBack });
			}
        }

    }
}
